﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DimsMapper.Modules;
using DimsMapper.UIClasses;

namespace DimsMapper
{
    public partial class MainForm : Form
    {
        //public void EnableDoubleBuffering()
        //{
        //   // Set the value of the double-buffering style bits to true.
        //   this.SetStyle(ControlStyles.DoubleBuffer | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);
        //   this.UpdateStyles();
        //}

        public MainForm()
        {
            InitializeComponent();
            //EnableDoubleBuffering();

            toolStrip2.Visible = false;
            tabMapsControl.TabPages.Clear();

            this.Text += Application.ProductVersion + " - by Mr.STALIN";
            //this.MouseWheel += MainForm_MouseWheel;

            MapDraw.DirectDrawInit(this);
            Main.InitializeMapper();

            if (Settings.MainGamePath() == string.Empty) {
                newTSButton.Enabled = false;
                openTSButton.Enabled = false;
            }
        }

        //private void MainForm_MouseWheel(System.Object sender, MouseEventArgs e)
        //{
        //    TabPage tb = tabMapsControl.SelectedTab;
        //    UserTab ut = (UserTab)tb.Controls[0];
        //    ut.MouseWheelDelta(e.Delta);
        //}

        private MapTab CurrentMapTab()
        {
            return (MapTab)tabMapsControl.SelectedTab.Tag;
        }

        private void SaveFileMap(bool saveAs)
        {
            TabPage tb = tabMapsControl.SelectedTab;
            if (tb == null) return;

            MapTab mt = (MapTab)tb.Tag;

            if (saveAs) {
                mapSaveFileDialog.InitialDirectory = Path.Combine(Settings.SaveDataFolder, "MAPS");
                mapSaveFileDialog.FileName = mt.MapName();
                if (mapSaveFileDialog.ShowDialog() == DialogResult.Cancel) return;

                if (!mt.SetMapFile(mapSaveFileDialog.FileName)) return;
                tb.Text = mt.MapName();
            }

            mt.MapSave();    
            mt.MapChangeState(false);

            tb.ToolTipText = mt.MapFile();
            SetDescriptionInfo(mt.MapFile());

            SaveButtonState(false);
        }

        private void SaveButtonState(bool state)
        {
            saveTSButton.Image = (state) ? Properties.Resources.saveHS : Properties.Resources.saveHS0;
        }

        private void DisableSaveButton()
        {
            if (tabMapsControl.TabCount == 0) {
                saveTSButton.Enabled = false;
                toolStrip2.Visible = false; 
            }
        }

        private bool CloseMapTab(int tabIndex)
        {
            MapTab mt = (MapTab)tabMapsControl.TabPages[tabIndex].Tag;
            bool result = mt.MapClose();

            if (!result) tabMapsControl.TabPages.RemoveAt(tabIndex);

            return result;
        }

        private void settingTSButton_Click(object sender, EventArgs e)
        {
            SettingForm form = new SettingForm();
            form.ShowDialog();
        }

        private void openTSButton_Click(object sender, EventArgs e)
        {
            List<string> listMaps = Main.OpenMapsList();
            listMaps.Sort();

            MapsListForm form = new MapsListForm(listMaps);
            if (form.ShowDialog() == DialogResult.OK) {
                int index = form.SelectMapsLoad();
                if (index == -1) return;

                MapTab map = Main.LoadMap(listMaps[index]);
                if (map == null) return;

                TabPage tb = new TabPage(map.MapName());
                tb.ToolTipText = map.MapFile();
                tb.Tag = map;

                UserTab ut = new UserTab(map);
                tb.Controls.Add(ut);
                ut.Dock = DockStyle.Fill;

                if (tabMapsControl.TabPages.Count == 0) {
                    SetDescriptionInfo(tb.ToolTipText);
                }

                toolStrip2.Visible = true;
                tabMapsControl.TabPages.Add(tb);
                tabMapsControl.SelectTab(tb);

                map.StartupViewportPosition();

                Main.SetMapsOpenCount(tabMapsControl.TabCount);

                map.MapChange += SaveButtonState;

                saveTSButton.Enabled = true;
            }
        }

        private void SetDescriptionInfo(string file)
        {
            if (file == null) {
                this.Text = "Dims Mapper II v" + Application.ProductVersion + " - by Mr.STALIN";
            } else {
                this.Text = "Dims Mapper II - Редактирование: " + ((file != string.Empty) ? file : "<NoFile>");
            }
        }

        private void tabMapsControl_Selected(System.Object sender, TabControlEventArgs e)
        {
            if (e.TabPage != null) {
                SetDescriptionInfo(e.TabPage.ToolTipText);
            } else {
                SetDescriptionInfo(null);
            }
        }

        private void tabMapsControl_MouseClick(System.Object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right) {
                for (int i = 0; i < tabMapsControl.TabCount; i++)
                {
                    if (tabMapsControl.GetTabRect(i).Contains(e.Location)) {
                        contextMenuTabs.Tag = i;
                        contextMenuTabs.Show(tabMapsControl, e.Location);
                        return;
                    }
                }
            }
        }

        private void tsButtonShow_CheckedChanged(System.Object sender, EventArgs e)
        {
            ToolStripButton btn = (ToolStripButton)sender;

            int n = int.Parse(btn.Tag.ToString());
            switch (n)
            {
                case 0:
                    btn.Image = (btn.Checked) ? Properties.Resources.items2 : Properties.Resources.items0;
                    break;
                case 1:
                    btn.Image = (btn.Checked) ? Properties.Resources.critters2 : Properties.Resources.critters0;
                    break;
                case 2:
                    btn.Image = (btn.Checked) ? Properties.Resources.scenery2 : Properties.Resources.scenery0;
                    break;
                case 3:
                    btn.Image = (btn.Checked) ? Properties.Resources.walls2 : Properties.Resources.walls0;
                    break;       
                case 4:
                    btn.Image = (btn.Checked) ? Properties.Resources.floor2 : Properties.Resources.floor0;
                    break;
                case 5:
                    btn.Image = (btn.Checked) ? Properties.Resources.misc2 : Properties.Resources.misc0;
                    break;
                case 6:
                    btn.Image = (btn.Checked) ? Properties.Resources.roof2 : Properties.Resources.roof0;
                    break;
            }
            CurrentMapTab().SetShowObjects(n, btn.Checked);
        }

        private void MainForm_KeyDown(System.Object sender, KeyEventArgs e)
        {
            TabPage tb = tabMapsControl.SelectedTab;
            if (tb == null) return;

            UserTab ut = (UserTab)tb.Controls[0];
            ut.KeyPressEvent(e, true);
        }

        private void MainForm_KeyUp(System.Object sender, KeyEventArgs e)
        {
            TabPage tb = tabMapsControl.SelectedTab;
            if (tb == null) return;

            UserTab ut = (UserTab)tb.Controls[0];
            ut.KeyPressEvent(e, false);
        }

        private void MainForm_KeyPress(System.Object sender, KeyPressEventArgs e)
        {
            
        }

        private void saveTSButton_ButtonClick(System.Object sender, EventArgs e)
        {
            SaveFileMap(false);
        }

        private void saveAsTSMenuItem_Click(System.Object sender, EventArgs e)
        {
            SaveFileMap(true);
        }

        private void tsMenuCloseMap_Click(System.Object sender, EventArgs e)
        {
            CloseMapTab((int)contextMenuTabs.Tag);
            DisableSaveButton();     
        }

        private void tsMenuCloseAll_Click(System.Object sender, EventArgs e)
        {
            for (int i = tabMapsControl.TabCount - 1; i >= 0; i--)
            {
                if (CloseMapTab(i)) break;
            }
            DisableSaveButton();
        }

        private void tsMenuCloseAllBut_Click(System.Object sender, EventArgs e)
        {
            for (int i = tabMapsControl.TabCount - 1; i >= 0; i--)
            {
                if (i != (int)contextMenuTabs.Tag && CloseMapTab(i)) break;
            }
        }

        private void ssbtnSelector_ButtonClick(System.Object sender, EventArgs e)
        {
            switch (Main.selectMode)
            {
                case 2:
                    tsMenuSelectObject.PerformClick();
                    break;
                case 0:
                    tsMenuSelectFloor.PerformClick();
                    
                    break;
                case 1:
                    tsMenuSelectRoof.PerformClick();
                    break;
            }
        }

        private void tsMenuSelectObject_Click(System.Object sender, EventArgs e)
        {
            ssbtnSelector.Image = Properties.Resources.selectObject;
            ssbtnSelector.Text = "Object";
            Main.selectMode = 0;
            MapTab.selectedTileRegion = 0;

            CurrentMapTab().MapUpdate();
        }

        private void tsMenuSelectFloor_Click(System.Object sender, EventArgs e)
        {
            ssbtnSelector.Image = Properties.Resources.selectFloor;
            ssbtnSelector.Text = "Floor";
            Main.selectMode = 1;

            CurrentMapTab().ClearSelectedObjects();
            CurrentMapTab().MapUpdate();
        }

        private void tsMenuSelectRoof_Click(System.Object sender, EventArgs e)
        {
            ssbtnSelector.Image = Properties.Resources.selectRoof;
            ssbtnSelector.Text = "Roof";
            Main.selectMode = 2;

            CurrentMapTab().ClearSelectedObjects();
            CurrentMapTab().MapUpdate();
        }

        private void tsbtnTopBlockers_Click(System.Object sender, EventArgs e)
        {
            Main.showOnTopBlockers = tsbtnTopBlockers.Checked;
            CurrentMapTab().MapUpdate();
        }
    }
}
